package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/cart")
public class CartController
{
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private CartService cartService;

    @GetMapping("/main")
    public String viewMain(@SessionAttribute("username") String username, Model model)
    {
        Cart cart = cartService.getCartByUsername(username);
        model.addAttribute("cart", cart);
        return "cart/main";
    }

    @GetMapping("/add")
    public String viewAdd(@RequestParam("itemId") String itemId, @SessionAttribute("username") String username)
    {
        if (itemId != null && catalogService.isItemInStock(itemId))
        {
            Cart cart = cartService.getCartByUsername(username);
            if (cart.containsItemId(itemId))
            {
                CartItem cartItem = cart.getItemById(itemId);
                cartService.updateCart(itemId, username, cartItem.getQuantity() + 1);
            } else cartService.insertCartItem(itemId, username);
        }
        return "redirect:/cart/main";
    }

    @GetMapping("/remove")
    public String viewRemove(@RequestParam("itemId") String itemId, @SessionAttribute("username") String username)
    {
        cartService.removeCartItem(itemId, username);
        return "redirect:/cart/main";
    }

    @PostMapping("/updateAjax")
    public void updateAjax(@SessionAttribute("username") String username, @RequestParam String itemId, @RequestParam int quantity)
    {
        cartService.updateCart(username, itemId, quantity);
    }
}
